<template>
  <div class="info-div">
    <div class="nav">
      <p class="title">我的账本</p>
      <div class="flex-container">
        <span class="text1">{{ year }}年</span>
        <span class="text2">收入</span>
        <span class="text2">支出</span>
      </div>
      <div class="flex-container">
        <div class="text1 income" @click="changeMonth()">
          {{ month }}月 ▼
        </div>
        <span class="text2 income">0.00</span>
        <span class="text2 expense">0.00</span>
      </div>

      <div class="card1">
        <div class="function">
          <div>
            <img class="pic" src="@/assets/icons/png/xiaoxi.png"/>
          </div>
          <div>
            <div class="span1">账单</div>
          </div>
        </div>
        <div class="function" @click="getMyAsset()">
          <div>
            <img class="pic" src="@/assets/icons/png/huizhang.png"/>
          </div>
          <div>
            <div class="span1" >资产</div>
          </div>
        </div>
        <div class="function">
          <div>
            <img class="pic" src="@/assets/icons/png/huizhang.png" @click="$router.push('/budget')"/>
          </div>
          <div>
            <div class="span1">预算</div>
          </div>
        </div>
        <div class="function">
          <div>
            <img class="pic" src="@/assets/icons/png/shezhi.png"/>
          </div>
          <div>
            <div class="span1">更多</div>
          </div>
        </div>
      </div>
    </div>
    <div class="itemList">
      <div class="mingxiMain"  v-for="(item, index) in itemList" :key="item.id">
        <div class="mingxiItemTop">
          <div class="mingxiItemTopLeft">
            {{item[0].addtime}}
          </div>
          <div class="mingxiItemTopRight">
            支出: {{item.accountSum}}
          </div>
        </div>
        <div class="mingxiItem" v-for="mingxi in item" :key="mingxi.budgetId" @touchstart="touchstart" @touchend="touchend(mingxi)">
          <div>
            <img class="my-icon" :src="require('@/assets/icons/budgettype1/' + mingxi.picture + '.png')"
                 :style="{ backgroundColor: 'rgb(251, 219, 68)'  }" @click="$parent.alterIcon(mingxi)"/>
          </div>
          <div class="itemDetail">
            <!-- Popconfirm 组件，但通常不直接绑定到 input 的 change 事件上 -->
            <el-popover :ref="`popover_name-${mingxi.budgetId}`" v-model="mingxi.showName" trigger="manual" >
              <div>
                <p>确定要更改此信息吗？</p>
                <div style="text-align: right; margin: 0">
                  <el-button  @click="handleCancel('name', mingxi)" type="text" size="mini">取消</el-button>
                  <el-button  @click="handleConfirm('name', mingxi)" type="primary" size="mini">确定</el-button>
                </div>
              </div>
              <el-input class="itemName" slot="reference" v-model="mingxi.remark" @input="openPopover(mingxi)"></el-input>
            </el-popover>
            <el-popover :ref="`popover_fy-${mingxi.budgetId}`" v-model="mingxi.showFy" trigger="manual">
              <p>确定要更改此信息吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button  @click="handleCancel('fy', mingxi)" type="text" size="mini">取消</el-button>
                <el-button  @click="handleConfirm('fy', mingxi)" type="primary" size="mini">确定</el-button>
              </div>
              <el-input class="itemFy" slot="reference" v-model="mingxi.amount" @input="mingxi.showFy=true"></el-input>
            </el-popover>
            <el-popover class="popoverInfo" :ref="`popover_info-${mingxi.budgetId}`">
              <div><el-button style="width: 100%;text-align: left;border: none;border-radius: 0px;" type="info" plain @click="handleInfo(mingxi,'showMxInfo')">查看</el-button></div>
              <div><el-button style="width: 100%;text-align: left;border: none;border-radius: 0px;" type="info" plain @click="handleInfo(mingxi,'delMxInfo')">删除</el-button></div>
              <div><el-button style="width: 100%;text-align: left;border: none;border-radius: 0px;" type="info" plain @click="handleInfo(mingxi,'upMxInfo')">修改</el-button></div>
              <el-button slot="reference" style="font-weight: bold;" size="mini" circle>···</el-button>
            </el-popover>
          </div>
        </div>
        <el-divider v-if="index < itemList.length-1"></el-divider>
      </div>
    </div>
    <el-dialog
        custom-class="cardInfo"
        append-to-body
        title="明细信息"
        :visible.sync="showInfo"
        width="90%"
        center
    >
      <el-form ref="form" :model="formMx" label-width="50px" :disabled="opType === 'showMxInfo'">
        <el-form-item>
          <div style="margin-left:20%">
            <img class="my-icon" :src="formMx.pic" :style="{ backgroundColor: 'rgb(251, 219, 68)'  }"/>
          </div>
          </el-form-item>
        <el-form-item label="类型">
          <el-input v-model="formMx.remark"></el-input>
        </el-form-item>
        <el-form-item label="金额">
          <el-input v-model="formMx.amount"></el-input>
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker
              v-model="formMx.addtime"
              align="right"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="showInfo = false">取 消</el-button>
        <el-button v-if="opType === 'upMxInfo'" type="primary" size="mini" @click="updateMxInfo()">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import router from "@/router";

import {pickerOptions, validateAmount} from "@/utils/common";

let userId = window.localStorage.getItem("userId");
import accountApi from "@/api/accountApi";
export default {
  name: 'detailView',
  data() {
    return {
      showInfo: false,
      loop: null,
      longTouch: false,
      popVisible: false,
      visible: true,
      itemList: [],
      curItemList: [],
      year: "",
      month: "",
      day: "",
      week: "",
      weeks : new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"),
      formMx: {},
      opType: '',
      pickerOptions: pickerOptions
    }
  },
  created() {
    // 初始化时间相关信息
    this.initTimeInfo();
    // 加载用户收支信息
    this.initData()
  },
  watch: {
    'itemList':  {
      handler(newVal, oldVal) {
        // 遍历 items 数组，更新每个内部数组的 sum
        this.itemList.forEach(item => {
          item.accountSum = item.reduce((acc, curr) => acc + (+curr.amount), 0);
        });
      },deep: true
    }
  },
  computed: {
  },
  methods: {
    // 跳转预算页面
    getBudget() {

    },
    getMyAsset() {
      router.push("/myAsset");
    },
    initData() {
      const param = {
        userId: userId,
        year: this.year,
        month: this.month
      }
      accountApi.queryBudget( param).then( res => {
        this.itemList =  res.data.data
        this.itemList.forEach(item => {
          item.forEach(mingxi => {
            mingxi.showFy = false; mingxi.showName = false; mingxi.showInfo = false;
          })
        })
        this.curItemList = JSON.parse(JSON.stringify(res.data.data));
        console.log(res.data)
      })
    },
    initTimeInfo() {
      let date = new Date();
      this.year = date.getFullYear();
      this.month = date.getMonth() + 1;
      this.day = date.getDate();
      this.week = this.weeks[new Date().getDay()];
      if (this.month < 10) {
        this.month = '0' + this.month
      }
    },
    changeMonth() {
      this.$parent.viewFrom = 'detailView'
      this.$parent.openDatePicker()
    },
    /**
     * 选择记账日期后操作
     */
    afterPickJzrq() {
      this.year = this.$parent.$refs.dateSelect.pickTime.year
      this.month = this.$parent.$refs.dateSelect.pickTime.month
      this.initData()
    },
    handleConfirm(type, mingxiItem) {
      const refTmp = `popover_${type}-${mingxiItem.budgetId}`
      if (type == 'fy' && !validateAmount(mingxiItem.amount)) {
        this.$message.error('请输入合法的金额')
        this.itemList = JSON.parse(JSON.stringify(this.curItemList))
        mingxiItem.showFy = false
        mingxiItem.showName = false
        return
      }
      const budgetParam = {
        budgetId: mingxiItem.budgetId,
        amount: mingxiItem.amount,
        remark: mingxiItem.remark,
      }
      accountApi.updateBudgetJbxx(budgetParam).then((res) => {
        if (res.data.code == 200) {
          this.$message.success('保存成功')
        } else {
          this.$message.error(res.data.message)
        }
      }).catch(() => {
        this.$message.error('系统异常')
      }).finally(() => {
        mingxiItem.showFy = false
        mingxiItem.showName = false
        this.initData()
      })
    },
    handleCancel(type, mingxiItem) {
      this.itemList = JSON.parse(JSON.stringify(this.curItemList))
      // const refTmp = `popover_${type}-${mingxiItem.budgetId}`
      // this.$refs[refTmp][0].doClose()
      // this.showPopName = false
      // this.showPopFy = false
      mingxiItem.showFy = false
      mingxiItem.showName = false
    },
    openPopover(mingxi){
      mingxi.showName = true
    },
    handleInfo(mingxi, opType) {
      this.opType = opType
      this.formMx = Object.assign({}, mingxi)
      this.formMx.pic = require('../../assets/icons/budgettype1/'+mingxi.picture+'.png')
      const refTmp = `popover_info-${mingxi.budgetId}`
      this.$refs[refTmp][0].doClose()
      console.log(this.formMx)
      if (opType === 'showMxInfo' || opType === 'upMxInfo') {
        this.showInfo = true
      } else if (opType === 'delMxInfo') {
        this.delMxInfo()
      }
    },
    delMxInfo() {
      const budgetParam = {
        budgetId: this.formMx.budgetId,
        delTag: 1,
      }
      accountApi.updateBudgetJbxx(budgetParam).then((res) => {
        if (res.data.code == 200) {
          this.$message.success('保存成功')
        } else {
          this.$message.error(res.data.message)
        }
      }).catch(() => {
        this.$message.error('系统异常')
      }).finally(() => {
        this.initData()
      })
    },
    updateMxInfo() {
      const budgetParam = {
        budgetId: this.formMx.budgetId,
        amount: this.formMx.amount,
        remark: this.formMx.remark,
        addtime: this.formMx.addtime
      }
      accountApi.updateBudgetJbxx(budgetParam).then((res) => {
        if (res.data.code == 200) {
          this.$message.success('保存成功')
        } else {
          this.$message.error(res.data.message)
        }
      }).catch(() => {
        this.$message.error('系统异常')
      }).finally(() => {
        this.initData()
        this.showInfo = false
      })
    },
    touchstart(){
      // 模拟长按
      clearTimeout(this.loop)
      this.longTouch = false
      this.loop = setTimeout(() => {
        this.longTouch = true  // 关键
      }, 600)
    },
    touchend(mingxi) {
      clearTimeout(this.loop) // 清空定时器，防止重复注册定时器
      if(!this.longTouch){
        return
      }
      mingxi.showInfo = true
      this.$forceUpdate()
      this.curItemList = JSON.parse(JSON.stringify(this.itemList))
      alert('待开发')
    },
  }
}
</script>


<style scoped lang="scss">
::v-deep .el-divider--horizontal {
  margin: 10px 0 ;
}

.nav {
  background-color: rgb(251, 219, 68);
  height: 150px;
}

.title {
  padding-top: 30px;
  font-weight: bold;
  font-size: larger;
}

.flex-container {
  margin-top: 15px;
  display: flex;
  justify-content: space-between; /* 如果需要元素之间的空间 */
  align-items: center; /* 垂直居中对齐 */
}

.text1 {
  flex: 0 0 30%; /* 不增长，不缩小，基础宽度为20% */
  margin-left: 3%;
  color: #8a8a8a;
  text-align: left; /* 确保文本居左（虽然默认就是）*/
}

.text2 {
  flex: 0 0 35%; /* 不增长，不缩小，基础宽度为40% */
  color: #8a8a8a;
  text-align: left; /* 收入和支出都居左 */
}

/* 如果需要区分收入和支出，可以为它们添加不同的样式 */
.income {
  /* 收入特有的样式 */
  color: #000000;
}

.expense {
  /* 支出特有的样式 */
  color: #000000;
}


.card1 {
  z-index: 999;
  width: 90%;
  height: 70px;
  background-color: white;
  margin: 10px auto;
  border-radius: 6px;
  display: flex;
  flex-wrap: wrap; /* 允许项目在容器中换行 */
  justify-content: space-around; /* 均匀分布项目 */
  align-items: center; /* 垂直居中对齐项目 */
}

.card1 .function {
  height: 80px;
}

.card1 .function .pic {
  height: 30px;
  width: 30px;
  margin-top: 10px;
}


.info-div {
  background-color: #fbfbfb;
  width: 100%;
  height: calc(100% - 60px);
  top: 0;
  position: fixed;
  overflow: hidden;
}

.itemList {
  z-index: 999;
  width: 99%;
  max-height: calc(100% - 260px);
  background-color: #ffffff;
  border-radius: 6px;
  margin-top: 60px;
  padding-bottom: 60px;
  /* 使用 flex 或 grid 布局来控制子元素 */
  position: absolute;
  flex-direction: column; /* 垂直布局 */
  overflow-y: auto; /* 如果内容超出，则添加垂直滚动条 */
}

.mingxiMain:not(:first-child)  {
  margin-top: 13px;
}

.mingxiMain:first-child  {
  margin-top: 5px;
}

.mingxiItemTop {
  margin-left: 10px;
  margin-right: 5px;
  font-size: 13px;
  color: #8a8a8a;
  display: flex;
  justify-content: space-between;

  .mingxiItemTopLeft {
    float: left;
  }

  .mingxiItemTopRight {
    float: right;
  }
}

.mingxiItem {
  margin-top: 8px;
  height: 46px;
  .my-icon {
    width: 30px;
    height: 30px;
    padding: 8px;
    margin-left: 15px;
    border-radius: 50%;
    float: left;
  }
  .itemDetail {
    font-size: 16px;
    height: 100%;
    display: flex;
    align-items: center;
    ::v-deep .el-input {
      margin-left: 5px;
      .el-input__inner{
        border: none;
      }
    }

    ::v-deep .el-input {
      .el-input__inner:focus{
        border: 1px solid #f6c134;
      }
    }

    .itemFy {
      width: 100px;
      text-align: right;
      margin-right: 5px;
    }
  }

  .popCnfirm_btns {
    padding-left: 40px;
  }

  .popCnfirm_btn {
    width: 30px;
    height: 14px;
    font-size: 14px;
  }

  .popCnfirm_content {
    text-align: center;
  }
  .info-card {
    position: absolute;
    width: 200px;
    left:0; /* 或其他值，根据具体布局调整 */
    margin-top: 150px;
    z-index: 1;
    text-align: left;
     /* 将卡片定位在 input 的左下方 */
    /* 其他样式，如宽度、背景色、边框等 */
  }
}

.popoverInfo {
  ::v-deep .el-popover {
    padding: 0!important;
  }
}

.my-icon {
  width: 60px;
  height: 60px;
  padding: 8px;
  margin-left: 5px;
  border-radius: 50%;
  left: 30%
}
.el-dialog__wrapper{
  ::v-deep .el-dialog__header{
    background-color: #ffdf66 !important;
  }
}
</style>